﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SurfaceAd.SDK.WP;

namespace ComicIsland.App.Views
{
    public partial class ComicSummaryPage : PhoneApplicationPage
    {
        private int comicId = 0, IsShellTile = 0;
        private string comicCoverUrl = string.Empty, comicTitle = string.Empty;
        private bool isLoadedComicSource = false, isLoadedRelationSource = false;

        public ComicSummaryPage()
        {
            InitializeComponent();
            this.surfaceAdComicSummary.InitAdControl(AdModeType.Debug);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string value;
            base.NavigationContext.QueryString.TryGetValue("comicId", out value);
            int.TryParse(value, out comicId);
            if (comicId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            string IsShellTileValue;
            base.NavigationContext.QueryString.TryGetValue("IsShellTile", out IsShellTileValue);
            int.TryParse(IsShellTileValue, out IsShellTile);
            //
            Task.Run(() =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    if (new LocalBookcaseInfoHelper().IsExist(this.comicId))
                        this.btnAddFav.Content = "取消收藏";
                    else
                        this.btnAddFav.Content = "添加收藏";
                });
            });
            //
            LoadComicSummary(comicId);

            this.LoadComicSource(this.comicId);
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (this.IsShellTile > 0)
            {
                //从磁贴进入应用
                NaviService.Navigate(ComicIslandPage.StartPage);
            }
            base.OnBackKeyPress(e);
        }



        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.pivotSummary == this.pivot.SelectedItem)
            {
                ApplicationBar.IsVisible = true;
                if (Application.Current.Host.Content.ActualHeight > 800)
                    this.surfaceAdComicSummary.Margin = new Thickness(0, 0, 0, 56);
                else
                    this.surfaceAdComicSummary.Margin = new Thickness(0, 0, 0, 72);
                if (!isLoadedComicSource)
                {
                    this.isLoadedComicSource = true;
                    this.LoadComicSource(this.comicId);
                }
            }
            else
            {
                ApplicationBar.IsVisible = false;
                this.surfaceAdComicSummary.Margin = new Thickness(0, 0, 0, 0);
                //if (this.pivotChapter == this.pivot.SelectedItem)
                //{
                //    if (!isLoadedComicSource)
                //    {
                //        this.isLoadedComicSource = true;
                //        this.LoadComicSource(this.comicId);
                //    }
                //    //
                //}
                //else 
                if (this.pivotRelation == this.pivot.SelectedItem)
                {
                    if (!isLoadedRelationSource)
                    {
                        this.isLoadedRelationSource = true;
                        this.LoadComicRelation();
                    }
                }
            }
        }


        #region 漫画详情
        public void LoadComicSummary(int comicId)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicsdetail_v2?bigbookid=", comicId.ToString(), "&", KEYS.REQUEST_QUERY_PLATFORM);

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailBase>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicsdetail != null && rootCharacterString.Info.Comicsdetail.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info.Comicsdetail;
                    if (items != null && items.Count > 0)
                    {
                        BindComicDetail(items);
                    }
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailBase>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicsdetail != null && rootCharacterString.Info.Comicsdetail.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info.Comicsdetail;
                            if (items != null && items.Count > 0)
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                BindComicDetail(items);
                            }
                        }

                        #endregion 获取结果处理

                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindComicDetail(ObservableCollection<JsonComicDetailComicsdetail> items)
        {
            JsonComicDetailComicsdetail item = (from p in items select p).FirstOrDefault<JsonComicDetailComicsdetail>();
            if (item == null)
                return;
            this.txtTitle.Text = item.BigbookName;
            this.gridSummary.DataContext = item;
            this.comicCoverUrl = item.Coverurl;
            this.comicTitle = item.BigbookName;
        }

        /// <summary>
        /// 话题评论
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridDiscuss_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = this.gridDiscuss.DataContext as JsonComicDetailComicsdetail;
            if (item != null)
            {
                NaviService.Navigate(ComicIslandPage.ComicDiscussionPage, string.Concat("?comicId=", item.BigbookId, "&title=", Uri.EscapeDataString(item.BigbookName)));
            }
        }

        /// <summary>
        /// 话题评论
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtDiscuss_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void btnAddFav_Click(object sender, RoutedEventArgs e)
        {
            var btn = (sender as Button);
            if (btn == null)
                return;
            var item = btn.DataContext as JsonComicDetailComicsdetail;
            if (item == null)
            {
                MessageToastManager.Show("无法获取到当前数据！");
                return;
            }
            var itemComicSource = this.llsComicSource.SelectedItem as Comicssource;
            if (!(itemComicSource != null && itemComicSource.BookId > 0 && !string.IsNullOrWhiteSpace(itemComicSource.SourceName)))
            {
                MessageToastManager.Show("无法获取到当前数据！");
                return;
            }
            //
            if (btn.Content.Equals("添加收藏"))
            {
                LocalBookcaseInfo bookcaseInfo = new LocalBookcaseInfo()
                {
                    ComicId = item.BigbookId,
                    ComicTitle = item.BigbookName,
                    Coverurl = item.Coverurl,
                    IsSync = false,
                    Status = LocalBookcaseStatus.Add.ToString(),
                    LocalUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD)
                };
                bookcaseInfo.BookId = itemComicSource.BookId;
                bookcaseInfo.SourceName = itemComicSource.SourceName;

                if (bookcaseInfo.ComicId > 0 || bookcaseInfo.BookId > 0)
                {
                    if (new LocalBookcaseInfoHelper().Add(bookcaseInfo))
                    {
                        this.btnAddFav.Content = "取消收藏";
                        //TODO 同步至服务器                        
                        new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Add, bookcaseInfo);
                    }
                }
            }
            else if (btn.Content.Equals("取消收藏"))
            {
                LocalBookcaseInfoHelper helper = new LocalBookcaseInfoHelper();
                if (item.BigbookId > 0 || itemComicSource.BookId > 0)
                {
                    var bookcaseInfo = helper.Get(item.BigbookId);
                    if (bookcaseInfo == null)
                    {
                        this.btnAddFav.Content = "添加收藏";
                        return;
                    }
                    bookcaseInfo.IsSync = false;
                    bookcaseInfo.Status = LocalBookcaseStatus.Delete.ToString();
                    bookcaseInfo.LocalUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD);
                    if (new LocalBookcaseInfoHelper().Update(bookcaseInfo))
                    {
                        this.btnAddFav.Content = "添加收藏";
                        //TODO 同步至服务器                        
                        new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Deleted, bookcaseInfo);
                    }
                }
            }
        }

        private void btnReader_Click(object sender, RoutedEventArgs e)
        {
            var item = this.btnReader.DataContext as JsonComicDetailComicsdetail;
            var itemComicSource = this.llsComicSource.SelectedItem as Comicssource;
            if (item == null || itemComicSource == null)
            {
                MessageToastManager.Show("无法获取到当前数据！");
                return;
            }
            if (!(item.BigbookId > 0 && itemComicSource.BookId > 0 && !string.IsNullOrWhiteSpace(itemComicSource.SourceName)))
            {
                MessageToastManager.Show("无法获取到当前数据！");
                return;
            }
            //到达章节页时，都要用bookid(资源站点)
            string param = string.Concat("?comicId=", this.comicId, "&bookId=", itemComicSource.BookId, "&comicSource=", Helper.UriEscapeDataString(itemComicSource.SourceName),
            "&comicCoverUrl=", Helper.UriEscapeDataString(this.comicCoverUrl), "&comicTitle=", Helper.UriEscapeDataString(this.comicTitle));
            NaviService.Navigate(ComicIslandPage.ComicDetailChapterPage, param);

        }



        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            string searchKeyword = Convert.ToString((sender as HyperlinkButton).Content);
            if (!string.IsNullOrWhiteSpace(searchKeyword))
            {
                NaviService.Navigate(ComicIslandPage.SearchBookAuthorPage, string.Concat("?searchKeyword=", Uri.EscapeDataString(searchKeyword), "&searchType=", ((int)KEYS.SearchType.Detail).ToString()));
            }
        }
        #endregion 漫画详情


        #region 漫画源站点

        public void LoadComicSource(int comicId)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/bigbooksource_v3?bigbookid=", comicId, "&", KEYS.REQUEST_QUERY_PLATFORM);

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicsDetailSource>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicssource != null && rootCharacterString.Info.Comicssource.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info.Comicssource;
                    if (items != null && items.Count > 0)
                    {
                        BindComicDetailSource(items);
                    }
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"comicssource\":{}") >= 0)
                        {
                            //无数据
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicsDetailSource>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicssource != null && rootCharacterString.Info.Comicssource.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info.Comicssource;
                            if (items != null && items.Count > 0)
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                BindComicDetailSource(items);
                            }
                        }
                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindComicDetailSource(ObservableCollection<Comicssource> items)
        {
            if (items != null && items.Count > 0)
            {
                var comicItem = new LocalBookcaseInfoHelper().Get(this.comicId);
                foreach (var item in items)
                {
                    if (comicItem != null)
                    {
                        if (item.BookId == comicItem.BookId)
                        {
                            item.IsUserSelectedFlag = true;
                            break;
                        }
                    }
                }
                this.llsComicSource.ItemsSource = items;
                this.txtComicSourceTotal.Text = string.Format("请选择漫画资源站阅读或下载（共{0}个）", items.Count.ToString());
                this.llsComicSource.SelectedItem = items[0];
            }
            else
            {
                this.txtComicSourceTotal.Text = "无信息！";
            }
        }


        private void gridComicSource_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Grid).DataContext as Comicssource;
            if (this.comicId <= 0 && item != null && item.BookId > 0)
            {
                return;
            }

            //NaviService.Navigate(ComicIslandPage.ComicDetailChapterPage, string.Concat("?comicId=", this.comicId, "&comicSource=", Uri.EscapeDataString(comicSource)));
            NaviService.Navigate(ComicIslandPage.ComicDetailChapterPage,
                string.Concat("?comicId=", this.comicId, "&bookId=", item.BookId, "&comicSource=", Uri.EscapeDataString(item.SourceName),
                "&comicCoverUrl=", Uri.EscapeDataString(this.comicCoverUrl), "&comicTitle=", Uri.EscapeDataString(this.comicTitle)));


        }

        #endregion 漫画源站点

        #region 相关推荐
        private void LoadComicRelation()
        {
            var item = this.gridSummary.DataContext as JsonComicDetailComicsdetail;
            if (item == null)
            {
                MessageToastManager.Show("未能获取当前漫画数据！");
                return;
            }
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            //&={"subjectname":["热血"],"mac":"ee:4a:5b:e4:f8:e4","authorname":["岸本齐史"],"bookid":["2"],"deviceid":"861934000827434","channelid":"91store"}
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/gltj_v2", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("\"subjectname\"", string.Format("[\"{0}\"]", Uri.EscapeDataString(item.SubjectName)));
            parameters.Add("\"authorname\"", string.Format("[\"{0}\"]", Uri.EscapeDataString(item.BigbookAuthor)));
            parameters.Add("\"bookid\"", string.Format("[\"{0}\"]", item.BigbookId));

            PostClientHelper proxy = new PostClientHelper(parameters, PostFormat.JsonJoin);
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(string.Concat(requestUrl, proxy.PostData.ToString())));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailRelationRecomm>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    BindComicRelation(rootCharacterString);
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    if (e.Error != null)
                    {
                        LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                        return;
                    }

                    #region 获取结果处理
                    string result = e.Result;
                    //LogHelper.LogInfo("JsonComicDetailRelationRecomm:", this.GetType(), MethodBase.GetCurrentMethod());
                    //LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());

                    if (string.IsNullOrWhiteSpace(result))
                    {
                        LogHelper.LogError("Result is empty.");
                        //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                        return;
                    }
                    //
                    if (result.StartsWith("exception:"))
                    {
                        LogHelper.LogError(result);
                        //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                        return;
                    }

                    result = result.Replace("\"authorBigBooks\":{}", "\"authorBigBooks\":[{}]");
                    result = result.Replace("\"subjectBigBooks\":{}", "\"subjectBigBooks\":[{}]");
                    result = result.Replace("\"topBigBooks\":{}", "\"topBigBooks\":[{}]");
                    LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());

                    //
                    var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailRelationRecomm>(result);
                    if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null))
                    {
                        //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                    }
                    else
                    {
                        cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                        BindComicRelation(rootCharacterString);
                    }
                    #endregion 获取结果处理
                }
                catch (Exception err)
                {
                }
                finally
                {
                    this.psbStatus.CloseStatusBar();
                }

            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }

        private void BindComicRelation(JsonComicDetailRelationRecomm items)
        {
            if (items.Info.TopBigBooks != null && items.Info.TopBigBooks.Count > 0 && items.Info.TopBigBooks[0].BigbookId > 0)
                this.llsEveryTop.ItemsSource = items.Info.TopBigBooks;
            if (items.Info.AuthorBigBooks != null && items.Info.AuthorBigBooks.Count > 0 && items.Info.AuthorBigBooks[0].BigbookId > 0)
                this.llsAuthor.ItemsSource = items.Info.AuthorBigBooks;
            if (items.Info.SubjectBigBooks != null && items.Info.SubjectBigBooks.Count > 0 && items.Info.SubjectBigBooks[0].BigbookId > 0)
                this.llsSubject.ItemsSource = items.Info.SubjectBigBooks;
        }

        private void llsEveryTop_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void llsAuthor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void llsSubject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void gridSubject_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Grid).DataContext as JsonComicDetailRelationRecommSubjectBigBook;
            if (item != null)
            {
                NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", item.BigbookId));
            }
        }

        private void gridAuthor_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Grid).DataContext as JsonComicDetailRelationRecommAuthorBigBook;
            if (item != null)
            {
                NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", item.BigbookId));
            }
        }

        private void gridEveryTop_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Grid).DataContext as JsonComicDetailRelationRecommTopBigBook;
            if (item != null)
            {
                NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", item.BigbookId));
            }
        }


        void SetPivotCategoryVisibility(double sujectOpactiyValue, double specialOpactiyValue, double authoOpactiyValue, Visibility sujectVisibilityValue, Visibility specialVisibilityValue, Visibility authorVisibilityValue)
        {
            this.gridPivotCategorySubject.Background.Opacity = sujectOpactiyValue;
            this.gridPivotCategorySpecial.Background.Opacity = specialOpactiyValue;
            this.gridPivotCategoryAuthor.Background.Opacity = authoOpactiyValue;
            this.llsSubject.Visibility = sujectVisibilityValue;
            this.llsAuthor.Visibility = specialVisibilityValue;
            this.llsEveryTop.Visibility = authorVisibilityValue;
        }

        private void gridPivotCategoryAuthor_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.txtSubjectName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            this.txtSpecialName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            this.txtAuthorName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentWhiteColor"])));
            SetPivotCategoryVisibility(0, 0, 1, Visibility.Collapsed, Visibility.Collapsed, Visibility.Visible);
        }

        private void gridPivotCategorySpecial_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.txtSubjectName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            this.txtSpecialName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentWhiteColor"])));
            this.txtAuthorName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            SetPivotCategoryVisibility(0, 1, 0, Visibility.Collapsed, Visibility.Visible, Visibility.Collapsed);
        }

        private void gridPivotCategorySubject_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.txtSubjectName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentWhiteColor"])));
            this.txtSpecialName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            this.txtAuthorName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            SetPivotCategoryVisibility(1, 0, 0, Visibility.Visible, Visibility.Collapsed, Visibility.Collapsed);
        }
        #endregion 相关推荐


        #region ApplicationBar
        /// <summary>
        /// 固定至桌面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarShellTile_Click(object sender, EventArgs e)
        {
            try
            {
                string navigationUrl = string.Format("/Views/{0}.xaml?comicId={1}&IsShellTile=1", ComicIslandPage.ComicSummaryPage.ToString(), this.comicId);
                ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault<ShellTile>((ShellTile p) => p.NavigationUri.ToString().Equals(navigationUrl));
                if (shellTile != null)
                {
                    MessageToastManager.Show("桌面已经有了这本漫画哦！");
                    return;
                }
                StandardTileData standardTileData = new StandardTileData();
                standardTileData.Title = this.comicTitle;
                standardTileData.BackgroundImage = (new Uri(this.comicCoverUrl, UriKind.Absolute));
                //standardTileData.BackBackgroundImage = (new Uri(this.comicCoverUrl, UriKind.Absolute));
                //standardTileData.BackTitle = this.comicTitle;
                //standardTileData.BackContent = this.comicTitle;
                ShellTile.Create(new Uri(navigationUrl, UriKind.Relative), standardTileData);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 分享 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarShared_Click(object sender, EventArgs e)
        {
            ShareData shareData = new ShareData();
            shareData.Content = string.Format("报告大王！，在漫画岛发现神作《{0}》，满满全是真(bi)爱(ge)！下载地址：http://www.manhuadao.cn", this.comicTitle);
            shareData.ImageSavedType = (int)ImageLocationType.Net;
            shareData.ImageUrl = this.comicCoverUrl;
            this.sharedControl.shareData = shareData;
            this.sharedControl.OnClose += delegate(object s1, EventArgs e1)
            {
                this.popupShared.IsOpen = false;
            };
            this.popupShared.IsOpen = true;
        }
        #endregion ApplicationBar

        /// <summary>
        /// 意见反馈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarFeedback_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.OtherComicFeedbackPage);
        }

        private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //44个一行，每行25px个高度
            if (this.gridComicDetailInfo.MaxHeight > 50)
            {
                this.gridComicDetailInfo.MaxHeight = 50;
                this.gridComicDetailInfo.MinHeight = 50;
                this.txtBriefLong.Visibility = System.Windows.Visibility.Collapsed;
                this.txtBriefShort.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                byte[] bytes = System.Text.Encoding.Unicode.GetBytes(this.txtBriefLong.Text.Trim());
                if (bytes.Length > 0)
                {
                    int heigith = 24 * ((bytes.Length / 44) + 1);
                    this.gridComicDetailInfo.MaxHeight = heigith;
                    this.gridComicDetailInfo.MinHeight = heigith;
                    this.txtBriefLong.Visibility = System.Windows.Visibility.Visible;
                    this.txtBriefShort.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    this.txtBriefLong.Visibility = System.Windows.Visibility.Collapsed;
                    this.txtBriefShort.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }












    }
}